package mc.web;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mc.bus.KsiegaGlowna;
import mc.domain.Swiadczenie;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class PrzegladajSwiadczenieController extends SimpleFormController {
	
	private KsiegaGlowna ksiegaglowna;
	private ResourceBundleMessageSource messagesource;

	@Override
	protected void initBinder(HttpServletRequest arg0, ServletRequestDataBinder arg1) throws Exception {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat(messagesource.getMessage("data.format", null, null));
	    dateFormat.setLenient(false);
	    arg1.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}


	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse arg1, Object command, BindException errors) throws Exception {
		
		String data_od_z = request.getParameter("data_od_z");
		String data_do = request.getParameter("data_do");
		logger.debug("Parametr refundacja: " + request.getParameter("refundacja"));
		boolean czyRefundowane = Boolean.parseBoolean(request.getParameter("refundacja"));
		logger.debug("Refundacja: " + czyRefundowane); 
		Map<Object, Object> model = new HashMap<Object, Object> ();
		logger.debug("########################data od " + data_od_z);
		
		if (data_od_z != null && data_do == null){
				
			List<Swiadczenie> platneSwiadczeniaByDate = ksiegaglowna.getPlatneSwiadczeniaByDate(data_od_z,czyRefundowane);
			logger.debug("ILOSC SWIADCZEN 1: " + platneSwiadczeniaByDate.size());
			model.put("swiadczenia", platneSwiadczeniaByDate);
			
		}
		
		else{
			List<Swiadczenie> platneSwiadczeniaBetweenDates = ksiegaglowna.getPlatneSwiadczeniaBetweenDates(data_od_z,data_do,czyRefundowane);
			logger.debug("ILOSC SWIADCZEN 2: " + platneSwiadczeniaBetweenDates.size());
			model.put("swiadczenia", platneSwiadczeniaBetweenDates);
						  
		}
		model.put("swiadczenie", command);
		model.put("data_od_z", data_od_z);
		model.put("data_do", data_do);
		logger.debug("Przekierowanie do widoku: "  + getSuccessView()); 
		
		return new ModelAndView(getSuccessView(),model);
	}
	
 
	public KsiegaGlowna getKsiegaglowna() {
		return ksiegaglowna;
	}

	public void setKsiegaglowna(KsiegaGlowna ksiegaglowna) {
		this.ksiegaglowna = ksiegaglowna;
	}
	
	public ResourceBundleMessageSource getMessagesource() {
		return messagesource;
	}


	public void setMessagesource(ResourceBundleMessageSource messagesource) {
		this.messagesource = messagesource;
	}

}
